<script setup lang="ts">
import { Message, FormInstance } from '@arco-design/web-vue'
import { useUserStore } from '@/store'
import type { RequestOption, UploadRequest } from '@arco-design/web-vue'
import { uploadFileUsingPost } from '@/api/fileController'
import { ref } from 'vue'
import { updateUserUsingPut } from '@/api/userController'

const userStore = useUserStore()
// 用户更新请求对象
const userUpdateRequest = ref<API.UserUpdateRequest>({
  id: userStore.user.id,
  avatar: '',
  nickname: '',
  tags: [],
  profile: ''
})
// 控制输入框显示状态
const showNicknameInput = ref(false)
const showTagsInput = ref(false)
const showProfileInput = ref(false)

// 表单数据
const formData = ref({
  nickname: '',
  tags: [] as string[],
  profile: ''
})

// 表单引用
const nicknameFormRef = ref<FormInstance>()
const profileFormRef = ref<FormInstance>()

// 昵称的校验规则
const nicknameRules = {
  nickname: [
    { required: false, message: '请输入昵称' },
    { maxLength: 16, message: '昵称不能超过16个字符' }
  ]
}

// 个人介绍校验规则
const profileRules = {
  profile: [
    { required: false, message: '请输入个人介绍' },
    { maxLength: 200, message: '个人介绍不能超过200个字符' }
  ]
}

// 处理修改昵称
const handleUpdateNickname = async () => {
  if (!nicknameFormRef.value) return
  try {
    const errorValid = await nicknameFormRef.value.validate()
    if (errorValid) {
      return
    }
    userUpdateRequest.value.id = userStore.user.id
    userUpdateRequest.value.tags = userStore.user.tags
    userUpdateRequest.value.nickname = formData.value.nickname
    const res: any = await updateUserUsingPut(userUpdateRequest.value)

    if (res.code === 0) {
      userStore.user.nickname = formData.value.nickname
      showNicknameInput.value = false
    } else {
      Message.error(res.message || '昵称修改失败')
    }
  } catch (error) {
    // 校验失败不处理，因为会显示校验错误信息
    if (error instanceof Error) {
      Message.error('昵称修改失败：' + error.message)
    }
  }
}

// 处理修改标签
const handleUpdateTags = async () => {
  try {
    if (formData.value.tags.length === 0 || formData.value.tags.length > 5) {
      Message.error('请设置1-5个标签')
      return
    }
    userUpdateRequest.value.id = userStore.user.id
    userUpdateRequest.value.tags = formData.value.tags
    const res: any = await updateUserUsingPut(userUpdateRequest.value)

    if (res.code === 0) {
      userStore.user.tags = formData.value.tags
      showTagsInput.value = false
    } else {
      Message.error(res.message || '标签修改失败')
    }
  } catch (error) {
    if (error instanceof Error) {
      Message.error('标签修改失败：' + error.message)
    }
  }
}

// 处理修改个人介绍
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  try {
    const errorValid = await profileFormRef.value.validate()
    if (errorValid) {
      return
    }
    userUpdateRequest.value.id = userStore.user.id
    userUpdateRequest.value.tags = userStore.user.tags
    userUpdateRequest.value.profile = formData.value.profile
    const res: any = await updateUserUsingPut(userUpdateRequest.value)

    if (res.code === 0) {
      userStore.user.profile = formData.value.profile
      showProfileInput.value = false
    } else {
      Message.error(res.message || '个人介绍修改失败')
    }
  } catch (error) {
    if (error instanceof Error) {
      Message.error('个人介绍修改失败：' + error.message)
    }
  }
}

// 修改 handleCancel 函数
const handleCancel = (type: 'nickname' | 'tags' | 'profile') => {
  if (type === 'nickname') {
    showNicknameInput.value = false
    formData.value.nickname = userStore.user.nickname || ''
  } else if (type === 'tags') {
    showTagsInput.value = false
    formData.value.tags = userStore.user.tags || []
  } else {
    showProfileInput.value = false
    formData.value.profile = userStore.user.profile || ''
  }
  userUpdateRequest.value = {}
}

// 修改 startEdit 函数
const startEdit = (type: 'nickname' | 'tags' | 'profile') => {
  if (type === 'nickname') {
    formData.value.nickname = userStore.user.nickname || ''
    showNicknameInput.value = true
  } else if (type === 'tags') {
    formData.value.tags = userStore.user.tags || []
    showTagsInput.value = true
  } else {
    formData.value.profile = userStore.user.profile || ''
    showProfileInput.value = true
  }
}

// 处理头像上传
const handleAvatarUpload = async (option: any) => {
  const file = option.fileItem.file
  // 验证文件大小
  if (file.size > 1024 * 1024) {
    Message.error('文件大小不能超过1M')
    return
  }

  // 验证文件类型
  const validTypes = ['image/jpeg', 'image/png']
  if (!validTypes.includes(file.type)) {
    Message.error('仅支持JPG,PNG')
    return
  }

  try {
    // 调用上传接口
    const avatar_data: any = await uploadFileUsingPost(file)
    if (!avatar_data) {
      Message.error('头像上传失败')
      return
    }
    userUpdateRequest.value.id = userStore.user.id
    userUpdateRequest.value.avatar = avatar_data.data
    console.log(userUpdateRequest.value)
    const res: any = await updateUserUsingPut(userUpdateRequest.value)
    if (res.code == 0) {
      await userStore.getUserInfo()
    } else {
      Message.error(res?.message || '头像上传失败')
    }
    userUpdateRequest.value = {}
    Message.success('头像上传成功')
  } catch (error) {
    Message.error('头像上传失败：' + error)
  }
}

// 标签颜色列表
const tagColors = ['blue', 'green', 'orange', 'purple', 'magenta']

defineExpose({})
</script>

<template>
  <div class="section-item">
    <div class="item-header">个人资料</div>
    <div class="item-content">
      <!-- 头像上传 -->
      <div class="info-row">
        <div class="info-label">头像</div>
        <div class="info-value">
          <div class="input-area">
            <div class="avatar-upload">
              <a-upload
                :image-preview="true"
                :show-file-list="false"
                :custom-request="handleAvatarUpload"
                accept="image/png,image/jpeg"
                :limit="1"
                :size="1024"
                :auto-upload="true"
                :key="userStore.user.avatar"
              >
                <template #upload-button>
                  <div class="avatar-wrapper">
                    <img
                      v-show="userStore.user.avatar"
                      :src="userStore.user.avatar"
                      class="avatar-image"
                      alt="avatar"
                    />
                  </div>
                </template>
              </a-upload>
              <div class="upload-tip">选择图片 仅支持JPG,PNG格式上传，大小不超过1M</div>
            </div>
          </div>
          <span class="info-tip">选择一张合适的照片作为头像，团队成员可以更容易认识你</span>
        </div>
      </div>

      <!-- 姓名（只读） -->
      <div class="info-row">
        <div class="info-label">姓名</div>
        <div class="info-value">
          <div class="input-area">
            <span class="value-text">{{ userStore.user.username }}</span>
          </div>
          <span class="info-tip">姓名不可修改</span>
        </div>
      </div>

      <!-- 昵称 -->
      <div class="info-row">
        <div class="info-label">昵称</div>
        <div class="info-value">
          <div class="input-area">
            <template v-if="showNicknameInput">
              <a-form ref="nicknameFormRef" :model="formData" :rules="nicknameRules">
                <a-form-item field="nickname">
                  <a-input
                    v-model="formData.nickname"
                    placeholder="请输入昵称"
                    allow-clear
                    :style="{ width: '240px' }"
                    :maxLength="16"
                  />
                </a-form-item>
              </a-form>
              <div class="action-buttons">
                <a-button type="primary" size="small" @click="handleUpdateNickname">
                  确定
                </a-button>
                <a-button size="small" @click="handleCancel('nickname')"> 取消 </a-button>
              </div>
            </template>
            <template v-else>
              <span class="value-text">{{ userStore.user.nickname || '未设置' }}</span>
              <a-button type="text" size="small" @click="startEdit('nickname')">
                {{ userStore.user.nickname ? '修改' : '立即添加' }}
              </a-button>
            </template>
          </div>
          <span class="info-tip">你也可以输入自己喜欢的昵称</span>
        </div>
      </div>

      <!-- 标签 -->
      <div class="info-row">
        <div class="info-label">标签</div>
        <div class="info-value">
          <div class="input-area">
            <template v-if="showTagsInput">
              <a-form ref="tagsFormRef" :model="formData">
                <a-form-item field="tags">
                  <a-input-tag
                    v-model="formData.tags"
                    placeholder="请输入标签"
                    :max-tag-count="5"
                    allow-clear
                    :style="{ width: '240px' }"
                  />
                </a-form-item>
              </a-form>
              <div class="action-buttons">
                <a-button type="primary" size="small" @click="handleUpdateTags"> 确定 </a-button>
                <a-button size="small" @click="handleCancel('tags')"> 取消 </a-button>
              </div>
            </template>
            <template v-else>
              <div class="tags-container" v-if="userStore.user.tags?.length">
                <a-tag
                  v-for="(tag, index) in userStore.user.tags"
                  :key="tag"
                  :color="tagColors[index % tagColors.length]"
                  size="small"
                >
                  {{ tag }}
                </a-tag>
              </div>
              <span v-else class="value-text">未设置</span>
              <a-button type="text" size="small" @click="startEdit('tags')">
                {{ userStore.user.tags?.length ? '修改' : '立即添加' }}
              </a-button>
            </template>
          </div>
          <span class="info-tip">请设置个人标签，让团队成员知道你的擅长</span>
        </div>
      </div>

      <!-- 个人介绍 -->
      <div class="info-row">
        <div class="info-label">个人介绍</div>
        <div class="info-value">
          <div class="input-area">
            <template v-if="showProfileInput">
              <a-form ref="profileFormRef" :model="formData" :rules="profileRules">
                <a-form-item field="profile">
                  <a-textarea
                    v-model="formData.profile"
                    placeholder="请输入个人介绍"
                    allow-clear
                    :style="{ width: '240px' }"
                    :max-length="200"
                    :rows="3"
                    show-word-limit
                  />
                </a-form-item>
              </a-form>
              <div class="action-buttons">
                <a-button type="primary" size="small" @click="handleUpdateProfile"> 确定 </a-button>
                <a-button size="small" @click="handleCancel('profile')"> 取消 </a-button>
              </div>
            </template>
            <template v-else>
              <span class="value-text profile-text">{{ userStore.user.profile || '未设置' }}</span>
              <a-button type="text" size="small" @click="startEdit('profile')">
                {{ userStore.user.profile ? '修改' : '立即添加' }}
              </a-button>
            </template>
          </div>
          <span class="info-tip">介绍一下你自己吧</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.section-item {
  background-color: #fff;
  border-radius: 4px;
}

.item-header {
  padding: 12px 20px;
  font-size: 15px;
  font-weight: 500;
  color: var(--color-text-1);
  border-bottom: 1px solid var(--color-border);
}

.item-content {
  padding: 0 20px;
}

.info-row {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid var(--color-border);
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  width: 80px;
  font-size: 14px;
  color: var(--color-text-2);
  line-height: 32px;
}

.info-value {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.input-area {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-tip {
  font-size: 13px;
  color: var(--color-text-3);
  width: 120px;
  text-align: right;
  flex-shrink: 0;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.avatar-wrapper {
  width: 160px;
  height: 160px;
  border: 1px dashed var(--color-border);
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  overflow: hidden;
}

.avatar-wrapper:hover {
  border-color: rgb(var(--primary-6));
  background: var(--color-fill-2);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: var(--color-text-3);
}

.avatar-placeholder .arco-icon {
  font-size: 24px;
}

.upload-tip {
  font-size: 13px;
  color: var(--color-text-3);
}

:deep(.arco-input-tag) {
  width: 240px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  height: 32px;
  align-items: center;
}

.value-text {
  font-size: 14px;
  color: var(--color-text-1);
}

.tags-container {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

:deep(.arco-tag) {
  margin: 0;
}

.profile-text {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
}

:deep(.arco-textarea-wrapper) {
  vertical-align: top;
}

:deep(.arco-textarea) {
  resize: none;
}
</style>
